package com.linjiahao.gateway.filter;

import com.google.gson.JsonObject;
import com.linjiahao.servicebase.common.BaseConstant;
import com.linjiahao.servicebase.exception.ErrorMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @ClassName AuthGlobalFilter
 * @Description: 网关全局鉴权拦截
 * @Author linjiahao
 * @Date 29/12/2021
 **/
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("请求路径为:{}",path);
        List<String> tokenList = request.getHeaders().get(BaseConstant.HEADER_TOKEN_KEY);
        if (antPathMatcher.match("/**/auth/**", path)) {
            if (null == tokenList) {
                ServerHttpResponse response = exchange.getResponse();
                return out(response);
            } else {
              log.info("接口鉴权token为：{}",tokenList.get(0) );
              if(!redisTemplate.hasKey(String.format(BaseConstant.USER_LOGIN_SUCCESS,tokenList.get(0)))){
                  ServerHttpResponse response = exchange.getResponse();
                  return out(response);
              }
            }
        }
        //内部服务接口，不允许外部访问
        if (antPathMatcher.match("/**/inner/**", path)) {
            ServerHttpResponse response = exchange.getResponse();
            return out(response);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", ErrorMessage.TOKEN_IS_NOT_VALIDATE.getErrorCode());
        message.addProperty("data", ErrorMessage.TOKEN_IS_NOT_VALIDATE.getMessage());
       byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
